﻿tTrawler.db = {
  init : function() {
    var file = Components.classes["@mozilla.org/file/directory_service;1"]
      .getService(Components.interfaces.nsIProperties)
      .get("ProfD", Components.interfaces.nsIFile);
      
    file.append(tTrawler.config["database"]);

    var storageService = Components.classes["@mozilla.org/storage/service;1"]
      .getService(Components.interfaces.mozIStorageService);
    
    tTrawler.db.connection = storageService.openDatabase(file);  
  },
  
  addRow :function(row) {
    var query = "INSERT INTO results VALUES ('"+row[0]+"', '"+ row[1] +"','"+row[2]+"','"+row[3]+"' ,'"+row[4]+"')";
  
    var statement = tTrawler.db.connection.createStatement(query);
    statement.execute();
	statement.reset();
  },
  
  getResults : function(sortBy, dir) {
  
    var r = [];
    var query = "SELECT * FROM results ORDER BY url DESC";
   
    if(sortBy && dir) {
      query += " ORDER BY " + sortBy + " " + dir;
    };
  
    var statement = tTrawler.db.connection.createStatement(query);
  
    while (statement.executeStep()) {
      var row = [];
      for (i=0;i<=4;i++) {
        row.push(statement.getString(i));
      };
      r.push(row);
    }; //r = ['a','b','c','d', 'e']; 
	statement.reset();
    return r;
  
  },
  
  clearResults : function() {
  var query = "DELETE FROM results";
  
    var statement = tTrawler.db.connection.createStatement(query);
    statement.execute();
	statement.reset();
  } 
}

